import 'package:demo1/model/conversation.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import '_models_db.dart';
import '../utils/sputil.dart';
import 'addressbookprovider.dart';
import 'chatdetailprovider.dart';
import '../provider/websocketprovider.dart';

class ChatManagerProvider with ChangeNotifier {
  late AddressBookProvider addressBookProvider;

  ChatManagerProvider(BuildContext context) {
    print("ChatManagerProvider");

    addressBookProvider =
        Provider.of<AddressBookProvider>(context, listen: false);

    WebSocketProvider().onChat = (data) async {
      String sessionId = data["session_id"];

      if (providers.containsKey(sessionId)) {
        providers[sessionId]?.receive(data);
      } else {

        var addressBook =
            await addressBookProvider.getAddressBook(context, data["from"]);
        startChat(addressBook);

        providers[sessionId]?.receive(data);
      }
    };

    WebSocketProvider().onPeers = (data) async{
      peers = data;

      checkToUserOnline();

      print("peers length:${peers.length}");

    };
  }

  final List<Conversation> conversations = <Conversation>[];
  ///peers
  ///id,name,user_agent
  List<dynamic> peers = <dynamic>[];

  int navigateIndex = 0;

  int chatIndex = -1;

  var spu = SpUtil();

  getCurrentConversation() {
    if (conversations.isEmpty) {
      spu.setString("toUserId", "");

      return null;
    } else {
      var conversation = conversations[chatIndex];

      spu.setString("toUserId", conversation.userId);

      return conversation;
    }
  }

  changeNavigate(int index) {
    navigateIndex = index;

    notifyListeners();
  }

  ///切换聊天
  changeChat(Conversation item) {
    chatIndex = conversations.indexOf(item);
    notifyListeners();
  }

  ///启动聊天
  startChat(AddressBookModel addressBook) {
    //第一选项卡是聊天界面
    navigateIndex = 0;
    Conversation item;

    if (conversations.isEmpty ||
        conversations
            .where((element) => element.userId == addressBook.Friendusername)
            .isEmpty) {
      item = Conversation(
          avatar: "images/avatar1.jpeg",
          title: addressBook.Friendname,
          des: "",
          updateAt: "",
          groupId: 0,
          userId: addressBook.Friendusername,
          type: 0);
      conversations.add(item);

      chatIndex = conversations.length - 1;
    } else {
      item = conversations
          .where((element) => element.userId == addressBook.Friendusername)
          .first;

      chatIndex = conversations.indexOf(item);
    }

    notifyListeners();
  }

  static final providers = <String, ChatDetailProvider>{};
  /// 为 聊天界面添加模型
  newDetailProvider(Conversation item) {
    ChatDetailProvider provider = ChatDetailProvider(item);
    providers[provider.sessionId] = provider;
    provider.checkUserOnline(peers);

    return provider;
  }

  checkToUserOnline(){
    providers.forEach((key, value) {

      value.checkUserOnline(peers);

    });
  }

}
